package com.demo.function.mybatis.mybatisplus.handler;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.demo.function.mybatis.mybatisplus.UserHolder;
import com.google.common.collect.Lists;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.NullValue;
import org.apache.commons.lang3.ObjectUtils;

import java.util.List;

/**
 * 多租户Handler
 */
public class MyTenantLineHandler implements TenantLineHandler {

    private final List<String> includeTables;

    public MyTenantLineHandler(List<String> includeTables) {
        this.includeTables = ObjectUtils.getIfNull(includeTables, Lists::newArrayList);
    }

    @Override
    public Expression getTenantId() {
        Long tenantId = UserHolder.get();
        return tenantId == null ? new NullValue() : new LongValue(tenantId);
    }

    @Override
    public boolean ignoreTable(String tableName) {
        // 判断需要拼接租户
        return !includeTables.contains(tableName);
    }
}
